﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace Pst_Backup_Agent
{
    public partial class FrmPstBackupAgent : Form
    {
        private ApplicationSettings _localSettings = new ApplicationSettings(ApplicationSettings.SourceSettings.Local);
        private ApplicationSettings _gpoSettings = new ApplicationSettings(ApplicationSettings.SourceSettings.GPO);
        private Utilities logger = new Utilities();
        private System.Text.RegularExpressions.Regex _subnetRegExp = new System.Text.RegularExpressions.Regex(@"^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$");

        public FrmPstBackupAgent()
        {
            //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
            //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
            InitializeComponent();

            Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            this.Text = "Pst Backup 2013 - v" + version.ToString();
            RegisterAddInInOutlookWhiteList();

            logger.IsLogActivated = this._localSettings.EventLogActivated;
            logger.LogSeverity = this._localSettings.EventLogSeverity;

            List<DateTime> thisWeek = GetWeekDays(DateTime.Today);
            foreach (DateTime day in thisWeek)
            {
                this.cmbBxWeekly.Items.Add(System.Globalization.DateTimeFormatInfo.CurrentInfo.GetDayName(day.DayOfWeek));
            }
        }

        public void BackupFiles()
        {
            FrmPstBackupAgent_Load(null, null);
            List<Utilities.RegistryEntry> pstFilesToSave = new List<Utilities.RegistryEntry>();
            List<Utilities.RegistryEntry> pstFilesNotToSave = new List<Utilities.RegistryEntry>();

            foreach (Utilities.RegistryEntry pstFile in this.chkLstBxPstFilesToSave.Items)
            {
                logger.LogEvent(30000, "Inspecting " + pstFile.SourcePath, 0, System.Diagnostics.EventLogEntryType.Information);
                if (pstFile.ToBackup && PstNeedtoBeSaved(pstFile.LastSuccessfulBackup))
                {
                    if (!String.IsNullOrEmpty(pstFile.DestinationPath) || !String.IsNullOrEmpty(this._localSettings.FilesAndFoldersDestinationPath))
                    {
                        logger.LogEvent(30000, pstFile.SourcePath + " is enlisted for a backup.", 0, System.Diagnostics.EventLogEntryType.Information);
                        pstFilesToSave.Add(pstFile);
                    }
                    else
                    {
                        logger.LogEvent(10000, pstFile.SourcePath + " will be ignored because no Destination Folder have been specified.", 2, System.Diagnostics.EventLogEntryType.Warning);
                        pstFilesNotToSave.Add(pstFile);
                    }
                }
                else
                {
                    logger.LogEvent(30000, pstFile.SourcePath + " is not enlisted for a backup.", 0, System.Diagnostics.EventLogEntryType.Information);
                    pstFilesNotToSave.Add(pstFile);
                }
            }
            FrmBackup frmBackup = new FrmBackup();

            if (!String.IsNullOrEmpty(this._localSettings.BackupAgentLogoPath))
            {
                logger.LogEvent(30000, "LogoPath is : " + this._localSettings.BackupAgentLogoPath, 0, System.Diagnostics.EventLogEntryType.Information);
                try
                {
                    if (this._localSettings.BackupAgentLogoPath.ToLower() == "akiolis group")
                    {
                        frmBackup.Logo = Properties.Resources.Logo_Akiolis_Group_128x62;
                    }
                    else
                        if (this._localSettings.BackupAgentLogoPath.ToLower() != "default logo")
                        {
                            Bitmap logo = new Bitmap(this._localSettings.BackupAgentLogoPath);
                            frmBackup.Logo = logo;
                        }
                        else
                            frmBackup.Logo = Properties.Resources.Pst_Backup_2013_128X128;
                }
                catch (Exception ex) { logger.LogEvent(30000, ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }
            }

            frmBackup.Backup(pstFilesToSave, pstFilesNotToSave, this._localSettings);
            if (pstFilesToSave.Count != 0)
            {
                frmBackup.ShowDialog();
            }
        }

        private bool PstNeedtoBeSaved(DateTime lastSuccessfulBackup)
        {
            int result = GetNewBackupDate(lastSuccessfulBackup).CompareTo(DateTime.Now);
            logger.LogEvent(30000, "Pst need to be save (" + lastSuccessfulBackup.ToString() + "): " + result.ToString(), 0, System.Diagnostics.EventLogEntryType.Information);
            return (result <= 0);
        }

        private DateTime GetNewBackupDate(DateTime lastSuccessfulBackup)
        {
            DateTime newBackupDate = DateTime.Now;

            switch (this._localSettings.SchedulePolicy.ToLower())
            {
                case "every":
                    newBackupDate = GetBackupDateEvery(lastSuccessfulBackup);
                    break;
                case "weekly":
                    newBackupDate = GetBackupDateWeekly(lastSuccessfulBackup);
                    break;
                case "monthly":
                    newBackupDate = GetBackupDateMonthly(lastSuccessfulBackup);
                    break;
                default:
                    break;
            }
            logger.LogEvent(30000, "Get new backup date for " + lastSuccessfulBackup.ToString() + " : " + newBackupDate.ToString(), 0, System.Diagnostics.EventLogEntryType.Information);
            return newBackupDate;
        }

        private DateTime GetBackupDateEvery(DateTime lastsuccessfulBackup)
        {
            DateTime newBackupDate = DateTime.Now;

            try
            {
                switch (this._localSettings.ScheduleEveryUnit.ToLower())
                {
                    case "days":
                        logger.LogEvent(30000, "Backup Policy is 'Every x Days'", 0, System.Diagnostics.EventLogEntryType.Information);
                        newBackupDate = lastsuccessfulBackup.AddDays((double)this._localSettings.ScheduleEveryInterval);
                        break;
                    case "weeks":
                        logger.LogEvent(30000, "Backup Policy is 'Every x Weeks'", 0, System.Diagnostics.EventLogEntryType.Information);
                        newBackupDate = lastsuccessfulBackup.AddDays((double)this._localSettings.ScheduleEveryInterval * 7);
                        break;
                    case "months":
                        logger.LogEvent(30000, "Backup Policy is 'Every x Months'", 0, System.Diagnostics.EventLogEntryType.Information);
                        newBackupDate = lastsuccessfulBackup.AddMonths(this._localSettings.ScheduleEveryInterval);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex) { logger.LogEvent(30000, ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }

            return newBackupDate;
        }

        private DateTime GetBackupDateWeekly(DateTime lastsuccessfulBackup)
        {
            DateTime newBackupDate = DateTime.Now;

            try
            {
                logger.LogEvent(30000, "Backup Policy is 'Weekly' on " + this._localSettings.ScheduleWeeklyDay.ToString(), 0, System.Diagnostics.EventLogEntryType.Information);
                List<DateTime> thisWeek = GetWeekDays(lastsuccessfulBackup);
                List<DateTime> nextWeek = GetWeekDays(thisWeek[0].AddDays(7));
                newBackupDate = nextWeek[this._localSettings.ScheduleWeeklyDay];
            }
            catch (Exception ex) { logger.LogEvent(30000, ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }

            return newBackupDate;
        }

        private DateTime GetBackupDateMonthly(DateTime lastsuccessfulBackup)
        {
            DateTime nextBackupDate = DateTime.Now;

            try
            {
                logger.LogEvent(30000, "Backup Policy is 'Monthly' on " + this._localSettings.ScheduleMonthlyDay.ToString(), 0, System.Diagnostics.EventLogEntryType.Information);
                DateTime nextMonth = new DateTime(lastsuccessfulBackup.Year, lastsuccessfulBackup.Month, 1).AddMonths(1);

                if (DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month) < this._localSettings.ScheduleMonthlyDay) // Not enought days in the next month.
                    nextBackupDate = new DateTime(nextMonth.Year, nextMonth.Month, DateTime.DaysInMonth(nextMonth.Year, nextMonth.Month)); // Schedule backup at the last day of the month.
                else
                    nextBackupDate = new DateTime(nextMonth.Year, nextMonth.Month, this._localSettings.ScheduleMonthlyDay); // Schedule backup for the next month.
            }
            catch (Exception ex) { logger.LogEvent(30000, ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }

            return nextBackupDate;
        }

        /// <summary>
        /// Select default value for ComboBox.
        /// </summary>
        private void SetDefaultSettings()
        {
            rdBtnEvery.Checked = true;
            cmbBxEvery.SelectedIndex = 0;
            nupEvery.Value = 7;

            cmbBxWeekly.SelectedIndex = 6;
            cmbBxEventLog.SelectedIndex = 1;
        }

        private void LoadSettingsFromRegistry()
        {
            chkLstBxPstFilesToSave.Items.Clear();
            List<Utilities.RegistryEntry> regEntries = Utilities.GetPstRegistryEntries();

            foreach (Utilities.RegistryEntry regEntry in regEntries)
            {
                if (!String.IsNullOrEmpty(regEntry.SourcePath))
                    chkLstBxPstFilesToSave.Items.Add(regEntry, regEntry.ToBackup);
            }
        }

        private void SetUI()
        {
            try
            {
                txtBxCommonDestination.Text = this._localSettings.FilesAndFoldersDestinationPath;
                this.chkBxCompress.Checked = this._localSettings.FilesAndFoldersCompressFiles;
                this.chkBxSaveNewPST.Checked = !String.IsNullOrEmpty(this._localSettings.FilesAndFoldersDestinationPath);
            }
            catch (Exception) { }

            try
            {

                switch (this._localSettings.SchedulePolicy.ToLower())
                {
                    case "every":
                        this.rdBtnEvery.Checked = true;
                        this.SetScheduleUI("rdBtnEvery");
                        this.nupEvery.Value = (Decimal)this._localSettings.ScheduleEveryInterval;

                        switch (this._localSettings.ScheduleEveryUnit.ToLower())
                        {
                            case "days":
                                this.cmbBxEvery.SelectedIndex = 0;
                                break;
                            case "weeks":
                                this.cmbBxEvery.SelectedIndex = 1;
                                break;
                            case "months":
                                this.cmbBxEvery.SelectedIndex = 2;
                                break;
                            default:
                                this.cmbBxEvery.SelectedIndex = -1;
                                break;
                        }
                        break;
                    case "weekly":
                        this.rdBtnWeekly.Checked = true;
                        this.cmbBxWeekly.SelectedIndex = this._localSettings.ScheduleWeeklyDay;
                        this.SetScheduleUI("rdBtnWeekly");
                        break;
                    case "monthly":
                        this.rdBtnMonthly.Checked = true;
                        this.nupMonthly.Value = (decimal)this._localSettings.ScheduleMonthlyDay;
                        this.SetScheduleUI("rdBtnMonthly");
                        break;
                    default:
                        break;
                }
            }
            catch (Exception) { }

            try
            {
                this.chkBxEventLog.Checked = this._localSettings.EventLogActivated || this._gpoSettings.IsEventLogSeverityDefine;
                switch (this._localSettings.EventLogSeverity.ToLower())
                {
                    case "debug":
                        this.cmbBxEventLog.SelectedIndex = 0;
                        break;
                    case "information":
                        this.cmbBxEventLog.SelectedIndex = 1;
                        break;
                    case "warning":
                        this.cmbBxEventLog.SelectedIndex = 2;
                        break;
                    case "error":
                        this.cmbBxEventLog.SelectedIndex = 3;
                        break;
                    default:
                        this.cmbBxEventLog.SelectedIndex = 3;
                        break;
                }

            }
            catch (Exception) { }

            try
            {
                this.chkBxReporting.Checked = !String.IsNullOrEmpty(this._localSettings.ReportingServer);
                this.txtBxReportingServerName.Text = this._localSettings.ReportingServer;
            }
            catch (Exception) { }

            try
            {
                this.chkBxDisplayLogo.Checked = !String.IsNullOrEmpty(this._localSettings.BackupAgentLogoPath);
                if (this.chkBxDisplayLogo.Checked)
                {
                    if (!String.IsNullOrEmpty(this._localSettings.BackupAgentLogoPath))
                    {
                        this.txtBxLogoLocation.Text = this._localSettings.BackupAgentLogoPath;
                        try
                        {
                            if (this._localSettings.BackupAgentLogoPath.ToLower() == "akiolis group")
                            {
                                this.pctBxLogo.Image = Properties.Resources.Logo_Akiolis_Group_128x62;
                            }
                            else
                            {
                                System.IO.FileInfo logoFile = new System.IO.FileInfo(this.txtBxLogoLocation.Text);
                                if (logoFile.Exists)
                                {
                                    Bitmap logo = new Bitmap(this.txtBxLogoLocation.Text);
                                    this.pctBxLogo.Image = logo;
                                }
                                else
                                    this.SetDefaultLogo();
                            }
                        }
                        catch (Exception)
                        {
                            this.SetDefaultLogo();
                        }
                    }
                    else
                    {
                        this.SetDefaultLogo();
                    }
                }
                else
                    this.txtBxLogoLocation.Text = String.Empty;

                this.chkBxDontBackupOverWan.Checked = this._localSettings.BackupAgentDontBackupThroughtWan;
                this.txtBxAdditionalSubnets.Text = this._localSettings.BackupAgentAdditionalSubnets;
                this.txtBxAdditionalSubnets.Enabled = this.chkBxDontBackupOverWan.Checked;
            }
            catch (Exception) { }
        }

        private void SetDefaultLogo()
        {
            this.txtBxLogoLocation.Text = "Default Logo";
            this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
            this.txtBxLogoLocation.ForeColor = Color.DarkGray;
            this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
        }

        private void LockUIasRequireByGPO()
        {
            btnBrowseCommonDestination.Enabled = this.chkBxSaveNewPST.Checked && !this._gpoSettings.IsFilesAndFoldersDestinationPathDefine;
            txtBxCommonDestination.Enabled = this.chkBxSaveNewPST.Checked && !this._gpoSettings.IsFilesAndFoldersDestinationPathDefine;
            this.chkBxCompress.Enabled = !this._gpoSettings.IsFilesAndFoldersCompressFilesDefine;
            chkBxSaveNewPST.Enabled = String.IsNullOrEmpty(this._gpoSettings.FilesAndFoldersDestinationPath);

            bool schedulePolicyDefine = !this._gpoSettings.IsSchedulePolicyDefine;
            this.rdBtnEvery.Enabled = schedulePolicyDefine;
            this.rdBtnWeekly.Enabled = schedulePolicyDefine;
            this.rdBtnMonthly.Enabled = schedulePolicyDefine;
            this.nupEvery.Enabled = this.rdBtnEvery.Checked && schedulePolicyDefine;
            this.cmbBxEvery.Enabled = this.rdBtnEvery.Checked && schedulePolicyDefine;
            this.cmbBxWeekly.Enabled = this.rdBtnWeekly.Checked && schedulePolicyDefine;
            this.nupMonthly.Enabled = this.rdBtnMonthly.Checked && schedulePolicyDefine;

            this.chkBxEventLog.Enabled = !this._gpoSettings.IsEventLogSeverityDefine;
            this.cmbBxEventLog.Enabled = this.chkBxEventLog.Checked && !this._gpoSettings.IsEventLogSeverityDefine;

            this.chkBxReporting.Enabled = String.IsNullOrEmpty(this._gpoSettings.ReportingServer);
            this.txtBxReportingServerName.Enabled = this.chkBxReporting.Checked && String.IsNullOrEmpty(this._gpoSettings.ReportingServer);

            this.chkBxDisplayLogo.Enabled = String.IsNullOrEmpty(this._gpoSettings.BackupAgentLogoPath);
            this.txtBxLogoLocation.Enabled = this.chkBxDisplayLogo.Checked && String.IsNullOrEmpty(this._gpoSettings.BackupAgentLogoPath);
            this.btnBrowseLogo.Enabled = this.chkBxDisplayLogo.Checked && String.IsNullOrEmpty(this._gpoSettings.BackupAgentLogoPath);
            this.chkBxDontBackupOverWan.Enabled = !this._gpoSettings.IsBackupAgentDontBackupThroughtWanDefine;
            this.txtBxAdditionalSubnets.Enabled = !this._gpoSettings.IsBackupAgentAdditionalSubnetsDefine;
        }

        private void SetScheduleUI(string radioButtonName)
        {
            switch (radioButtonName)
            {
                case "rdBtnEvery":
                    this.nupEvery.Enabled = true;
                    this.cmbBxEvery.Enabled = true;
                    this.cmbBxWeekly.Enabled = false;
                    this.nupMonthly.Enabled = false;
                    break;
                case "rdBtnWeekly":
                    this.nupEvery.Enabled = false;
                    this.cmbBxEvery.Enabled = false;
                    this.cmbBxWeekly.Enabled = true;
                    this.nupMonthly.Enabled = false;
                    break;
                case "rdBtnMonthly":
                    this.nupEvery.Enabled = false;
                    this.cmbBxEvery.Enabled = false;
                    this.cmbBxWeekly.Enabled = false;
                    this.nupMonthly.Enabled = true;
                    break;
                default:
                    break;
            }
        }

        private List<DateTime> GetWeekDays(DateTime dayOfWeek)
        {
            List<DateTime> thisWeek = new List<DateTime>();

            int days = dayOfWeek.DayOfWeek - System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
            DateTime dt = dayOfWeek.AddDays(-days);
            thisWeek.Add(dt);
            thisWeek.AddRange(new DateTime[] { dt.AddDays(1), dt.AddDays(2), dt.AddDays(3), dt.AddDays(4), dt.AddDays(5), dt.AddDays(6) });

            return thisWeek;
        }

        private void UpdateLocalSettingsWithUI()
        {
            if (!this._gpoSettings.IsFilesAndFoldersDestinationPathDefine)
            {
                if (!this.chkBxSaveNewPST.Checked)
                    this.txtBxCommonDestination.Text = String.Empty;
                this._localSettings.FilesAndFoldersDestinationPath = Utilities.GetFormattedFolder(this.txtBxCommonDestination.Text);
            }

            if (!this._gpoSettings.IsFilesAndFoldersCompressFilesDefine)
                this._localSettings.FilesAndFoldersCompressFiles = this.chkBxCompress.Checked;

            if (!this._gpoSettings.IsSchedulePolicyDefine)
            {
                if (this.rdBtnEvery.Checked)
                {
                    this._localSettings.SchedulePolicy = "Every";
                    this._localSettings.ScheduleEveryInterval = (int)this.nupEvery.Value;
                    switch (this.cmbBxEvery.SelectedIndex)
                    {
                        case 0:
                            this._localSettings.ScheduleEveryUnit = "Days";
                            break;
                        case 1:
                            this._localSettings.ScheduleEveryUnit = "Weeks";
                            break;
                        case 2:
                            this._localSettings.ScheduleEveryUnit = "Months";
                            break;
                        default:
                            this._localSettings.ScheduleEveryUnit = "Days";
                            break;
                    }

                }
                else if (this.rdBtnWeekly.Checked)
                {
                    this._localSettings.SchedulePolicy = "Weekly";
                    this._localSettings.ScheduleWeeklyDay = this.cmbBxWeekly.SelectedIndex;
                }
                else if (this.rdBtnMonthly.Checked)
                {
                    this._localSettings.SchedulePolicy = "Monthly";
                    this._localSettings.ScheduleMonthlyDay = (int)this.nupMonthly.Value;
                }
            }

            if (!this._gpoSettings.IsEventLogSeverityDefine)
            {
                this._localSettings.EventLogActivated = this.chkBxEventLog.Checked;
                if (this.cmbBxEventLog.SelectedIndex != -1)
                {
                    // Debug  Information Warning Error

                    switch (this.cmbBxEventLog.SelectedIndex)
                    {
                        case 0:
                            this._localSettings.EventLogSeverity = "Debug";
                            break;
                        case 1:
                            this._localSettings.EventLogSeverity = "Information";
                            break;
                        case 2:
                            this._localSettings.EventLogSeverity = "Warning";
                            break;
                        case 3:
                            this._localSettings.EventLogSeverity = "Error";
                            break;
                        default:
                            this._localSettings.EventLogSeverity = "Error";
                            break;
                    }
                }
            }

            if (String.IsNullOrEmpty(this._gpoSettings.ReportingServer))
            {
                if (!this.chkBxReporting.Checked)
                    this.txtBxReportingServerName.Text = String.Empty;
                this._localSettings.ReportingServer = this.txtBxReportingServerName.Text;
            }

            this._localSettings.BackupAgentLogoPath = this.txtBxLogoLocation.Text;

            if (!this._gpoSettings.IsBackupAgentDontBackupThroughtWanDefine)
            {
                this._localSettings.BackupAgentDontBackupThroughtWan = this.chkBxDontBackupOverWan.Checked;
            }

            if (!this._gpoSettings.IsBackupAgentAdditionalSubnetsDefine)
            {
                this._localSettings.BackupAgentAdditionalSubnets = this.txtBxAdditionalSubnets.Text;
            }
        }

        private void SavePSTFilesSettings()
        {
            try
            {
                for (int i = 0; i < this.chkLstBxPstFilesToSave.Items.Count; i++)
                {
                    Utilities.RegistryEntry regEntry = (Utilities.RegistryEntry)this.chkLstBxPstFilesToSave.Items[i];
                    regEntry.ToBackup = this.chkLstBxPstFilesToSave.CheckedItems.Contains(this.chkLstBxPstFilesToSave.Items[i]);
                    SavePSTFilesSettingsToRegistry(regEntry);
                }
            }
            catch (Exception ex) { logger.LogEvent(30000, "Error when saving PstFiles Settings : " + ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }
        }

        private void SavePSTFilesSettingsToRegistry(Utilities.RegistryEntry regEntryToSave)
        {
            try
            {
                Registry.SetValue(regEntryToSave.FullRegistryPath, "DestinationPath", Utilities.GetFormattedFolder(regEntryToSave.DestinationPath));
                Registry.SetValue(regEntryToSave.FullRegistryPath, "SourcePath", regEntryToSave.SourcePath);
                Registry.SetValue(regEntryToSave.FullRegistryPath, "ToBackup", regEntryToSave.ToBackup.ToString());
            }
            catch (Exception ex) { logger.LogEvent(30000, "Error when writting pst file settings into registry : " + ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }
        }

        private void RegisterAddInInOutlookWhiteList()
        {
            try
            {
                Microsoft.Win32.RegistryKey baseKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\15.0\Outlook\Resiliency\DoNotDisableAddinList", true);
                if (baseKey == null)
                    baseKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Office\15.0\Outlook\Resiliency\DoNotDisableAddinList");
                object regValue = baseKey.GetValue("Pst Backup 2013");
                if (regValue == null)
                    baseKey.SetValue("Pst Backup 2013", 1, RegistryValueKind.DWord);
                baseKey.Close();
            }
            catch (Exception ex) { logger.LogEvent(30000, ex.Message, 0, System.Diagnostics.EventLogEntryType.Error); }
        }

        #region {Data Validation}

        private void ValidateData()
        {
            this.btnApply.Enabled = ValidateFilesAndFoldersTab() && ValidateScheduleTab() && ValidateEventTab() && ValidateReportTab() && ValidateBackupAgentTab();
        }

        private bool ValidateFilesAndFoldersTab()
        {
            bool allPSTFileHaveaDestination = true;

            if (String.IsNullOrEmpty(this.txtBxCommonDestination.Text))
            {
                foreach (Utilities.RegistryEntry regEntry in this.chkLstBxPstFilesToSave.Items)
                {
                    if (regEntry.ToBackup && String.IsNullOrEmpty(regEntry.DestinationPath))
                        allPSTFileHaveaDestination = false;
                }
            }
            return (allPSTFileHaveaDestination && (!this.chkBxSaveNewPST.Checked || !String.IsNullOrEmpty(this.txtBxCommonDestination.Text)));
        }

        private bool ValidateScheduleTab()
        {
            bool result = false;

            if (this.rdBtnEvery.Checked)
            {
                result = (this.nupEvery.Value >= 1 && this.nupEvery.Value <= 365 && this.cmbBxEvery.SelectedIndex != -1);
            }
            if (this.rdBtnWeekly.Checked)
            {
                result = this.cmbBxWeekly.SelectedIndex != -1;
            }
            if (this.rdBtnMonthly.Checked)
            {
                result = this.nupMonthly.Value >= 1 && this.nupMonthly.Value <= 31;
            }

            return result;
        }

        private bool ValidateEventTab()
        {
            return (!this.chkBxEventLog.Checked || this.cmbBxEventLog.SelectedIndex != -1);
        }

        private bool ValidateReportTab()
        {
            return (!this.chkBxReporting.Checked || !String.IsNullOrEmpty(this.txtBxReportingServerName.Text));
        }

        private bool ValidateBackupAgentTab()
        {
            bool allAdditionalsubnetsAreOk = true;

            if (!String.IsNullOrEmpty(txtBxAdditionalSubnets.Text))
            {
                string[] subnets = this.txtBxAdditionalSubnets.Text.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string subnet in subnets)
                {
                    if (!_subnetRegExp.IsMatch(subnet))
                        allAdditionalsubnetsAreOk = false;
                }
            }
            this.txtBxAdditionalSubnets.BackColor = allAdditionalsubnetsAreOk ? SystemColors.Window : Color.OrangeRed;

            return ((!this.chkBxDisplayLogo.Checked || !String.IsNullOrEmpty(this.txtBxLogoLocation.Text)) && allAdditionalsubnetsAreOk);
        }

        #endregion {Data Validation}

        #region (UI managment)

        private void FrmPstBackupAgent_Load(object sender, EventArgs e)
        {
            SetDefaultSettings();
            LoadSettingsFromRegistry();
            _localSettings.OverrideLocalSettingsWithGPOSettings(_gpoSettings);
            _localSettings.SaveLocalSettings();
            SetUI();
            LockUIasRequireByGPO();
        }

        private void txtBxLogoLocation_Enter(object sender, EventArgs e)
        {
            txtBxLogoLocation.SelectAll();
        }

        private void chkLstBxPstFilesToSave_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Utilities.RegistryEntry regEntry = (Utilities.RegistryEntry)chkLstBxPstFilesToSave.SelectedItem;
                txtBxDestinationPath.Text = regEntry.DestinationPath;
            }
            catch (Exception)
            {
                txtBxDestinationPath.Clear();
            }
        }

        private void rdBtnEvery_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rdBtnClicked = (RadioButton)sender;
            this.SetScheduleUI(rdBtnClicked.Name);
            ValidateData();
        }

        private void txtBxDestinationPath_Enter(object sender, EventArgs e)
        {
            txtBxDestinationPath.SelectAll();
        }

        private void btnBrowseDestination_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fldBrowser = new FolderBrowserDialog();

            if (!String.IsNullOrEmpty(this.txtBxDestinationPath.Text))
                fldBrowser.SelectedPath = Utilities.TranslateDestinationFolder(this.txtBxDestinationPath.Text);

            try
            {
                if (fldBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.txtBxDestinationPath.Text = fldBrowser.SelectedPath;
                    if (this.chkLstBxPstFilesToSave.SelectedIndex != -1)
                    {
                        Utilities.RegistryEntry regEntry = (Utilities.RegistryEntry)chkLstBxPstFilesToSave.SelectedItem;

                        regEntry.DestinationPath = txtBxDestinationPath.Text;
                        chkLstBxPstFilesToSave.Items[chkLstBxPstFilesToSave.SelectedIndex] = regEntry;
                    }
                }

            }
            catch (Exception) { }
        }

        private void btnBrowseCommonDestination_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fldBrowser = new FolderBrowserDialog();

            if (!String.IsNullOrEmpty(this.txtBxCommonDestination.Text))
                fldBrowser.SelectedPath = Utilities.TranslateDestinationFolder(this.txtBxCommonDestination.Text);

            try
            {
                if (fldBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    this.txtBxCommonDestination.Text = fldBrowser.SelectedPath;
                }

            }
            catch (Exception) { }
        }

        private void txtBxDestinationPath_TextChanged(object sender, EventArgs e)
        {
            try
            {
                Utilities.RegistryEntry regEntry = (Utilities.RegistryEntry)chkLstBxPstFilesToSave.SelectedItem;
                regEntry.DestinationPath = txtBxDestinationPath.Text;
                this.chkLstBxPstFilesToSave.Items[this.chkLstBxPstFilesToSave.SelectedIndex] = regEntry;
            }
            catch (Exception) { }
            this.ValidateData();
            //if (!string.IsNullOrEmpty(this.txtBxDestinationPath.Text))
            //    this._localSettings.FilesAndFoldersDestinationPath = this.txtBxDestinationPath.Text;
        }

        private void nupEvery_ValueChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void cmbBxEvery_SelectedIndexChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void cmbBxWeekly_SelectedIndexChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void nupMonthly_ValueChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void chkBxEventLog_CheckedChanged(object sender, EventArgs e)
        {
            this.cmbBxEventLog.Enabled = this.chkBxEventLog.Checked;
            ValidateData();
        }

        private void cmbBxEventLog_SelectedIndexChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void chkBxReporting_CheckedChanged(object sender, EventArgs e)
        {
            this.txtBxReportingServerName.Enabled = this.chkBxReporting.Checked;
            if (!this.chkBxReporting.Checked)
                this.txtBxReportingServerName.Text = String.Empty;
            ValidateData();
        }

        private void txtBxReportingServerName_TextChanged(object sender, EventArgs e)
        {
            ValidateData();
        }

        private void chkBxDisplayLogo_CheckedChanged(object sender, EventArgs e)
        {
            this.txtBxLogoLocation.Enabled = this.chkBxDisplayLogo.Checked;
            this.btnBrowseLogo.Enabled = this.chkBxDisplayLogo.Checked;

            if (chkBxDisplayLogo.Checked)
            {
                if (String.IsNullOrEmpty(this.txtBxLogoLocation.Text) || !System.IO.File.Exists(this.txtBxLogoLocation.Text))
                {
                    this.txtBxLogoLocation.Text = "Default Logo";
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
                    this.txtBxLogoLocation.ForeColor = Color.DarkGray;
                    this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
                }
                else
                {
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular);
                    this.txtBxLogoLocation.ForeColor = Color.Black;
                }
            }
            else
            {
                this.pctBxLogo.Image = null;
                this.txtBxLogoLocation.Text = String.Empty;
            }
            ValidateData();
        }

        private void txtBxLogoLocation_TextChanged(object sender, EventArgs e)
        {
            this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular);
            this.txtBxLogoLocation.ForeColor = Color.Black;

            this.ValidateData();
        }

        private void chkBxDontBackupOverWan_CheckedChanged(object sender, EventArgs e)
        {
            this.txtBxAdditionalSubnets.Enabled = this.chkBxDontBackupOverWan.Checked;
            ValidateData();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtBxReportingFilename_Click(object sender, EventArgs e)
        {
            this.txtBxReportingServerName.SelectAll();
        }

        private void txtBxReportingServerName_Enter(object sender, EventArgs e)
        {
            this.txtBxReportingServerName.SelectAll();
        }

        private void ValidateNupEntry(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(((Control)sender).Text))
            {
                ((NumericUpDown)sender).Text = ((NumericUpDown)sender).Value.ToString();
                ((NumericUpDown)sender).Refresh();
            }
        }

        private void btnBrowseReport_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fldBrowser = new FolderBrowserDialog();

            if (!String.IsNullOrEmpty(txtBxReportingServerName.Text))
                fldBrowser.SelectedPath = Utilities.TranslateDestinationFolder(txtBxReportingServerName.Text);

            if (fldBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtBxReportingServerName.Text = fldBrowser.SelectedPath;
            }
            ValidateData();
        }

        private void btnBrowseLogo_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileBrowser = new OpenFileDialog();

            fileBrowser.Filter = "Images|*.png;*.jpeg;*.jpg;*.bmp;*.gif;*.tif";

            if (!String.IsNullOrEmpty(txtBxLogoLocation.Text))
            {
                try
                {
                    fileBrowser.InitialDirectory = txtBxLogoLocation.Text.Substring(0, txtBxLogoLocation.Text.LastIndexOf('\\'));
                    fileBrowser.FileName = txtBxLogoLocation.Text.Substring(txtBxLogoLocation.Text.LastIndexOf('\\') + 1);
                }
                catch (Exception) { }
            }

            if (fileBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtBxLogoLocation.Text = fileBrowser.FileName;

                if (String.IsNullOrEmpty(this.txtBxLogoLocation.Text))
                {
                    this.txtBxLogoLocation.Text = "Default Logo";
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
                    this.txtBxLogoLocation.ForeColor = Color.DarkGray;
                    this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
                }
                else
                {
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular);
                    this.txtBxLogoLocation.ForeColor = Color.Black;
                    try
                    {
                        Bitmap logo = new Bitmap(this.txtBxLogoLocation.Text);
                        this.pctBxLogo.Image = logo;
                    }
                    catch (Exception)
                    {
                        this.txtBxLogoLocation.Text = "Default Logo";
                        this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
                        this.txtBxLogoLocation.ForeColor = Color.DarkGray;
                        this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
                    }
                }
            }
            ValidateData();
        }

        private void txtBxLogoLocation_Leave(object sender, EventArgs e)
        {
            if (this.chkBxDisplayLogo.Checked)
            {
                if (String.IsNullOrEmpty(this.txtBxLogoLocation.Text) || !System.IO.File.Exists(this.txtBxLogoLocation.Text))
                {
                    this.txtBxLogoLocation.Text = "Default Logo";
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
                    this.txtBxLogoLocation.ForeColor = Color.DarkGray;
                    this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
                }
                else
                {
                    this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular);
                    this.txtBxLogoLocation.ForeColor = Color.Black;

                    try
                    {
                        Bitmap logo = new Bitmap(this.txtBxLogoLocation.Text);
                        this.pctBxLogo.Image = logo;
                    }
                    catch (Exception)
                    {
                        this.txtBxLogoLocation.Text = "Default Logo";
                        this.txtBxLogoLocation.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Italic);
                        this.txtBxLogoLocation.ForeColor = Color.DarkGray;
                        this.pctBxLogo.Image = Properties.Resources.Pst_Backup_2013_128X128;
                    }
                }
            }
            ValidateData();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            this.UpdateLocalSettingsWithUI();
            this._localSettings.SaveLocalSettings();
            this.SavePSTFilesSettings();
            this.Close();

            List<Utilities.RegistryEntry> pstFiles = new List<Utilities.RegistryEntry>();

            foreach (Utilities.RegistryEntry pstFile in this.chkLstBxPstFilesToSave.Items)
            {
                if (pstFile.ToBackup)
                    pstFiles.Add(pstFile);
            }
        }

        private void txtBxDestinationPath_Leave(object sender, EventArgs e)
        {
            try
            {
                Utilities.RegistryEntry regEntry = (Utilities.RegistryEntry)chkLstBxPstFilesToSave.SelectedItem;

                regEntry.DestinationPath = txtBxDestinationPath.Text;
                chkLstBxPstFilesToSave.Items[chkLstBxPstFilesToSave.SelectedIndex] = regEntry;
            }
            catch (Exception) { }
        }

        private void chkBxSaveNewPST_CheckedChanged(object sender, EventArgs e)
        {
            this.txtBxCommonDestination.Enabled = this.chkBxSaveNewPST.Checked;
            this.btnBrowseCommonDestination.Enabled = this.chkBxSaveNewPST.Checked;
            ValidateData();
        }

        private void chkLstBxPstFilesToSave_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            try
            {
                Utilities.RegistryEntry selectedItem = (Utilities.RegistryEntry)this.chkLstBxPstFilesToSave.SelectedItem;
                selectedItem.ToBackup = (e.NewValue == CheckState.Checked);
                this.chkLstBxPstFilesToSave.Items[this.chkLstBxPstFilesToSave.SelectedIndex] = selectedItem;
                this.ValidateData();
            }
            catch (Exception) { };
        }

        private void txtBxCommonDestination_TextChanged(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        private void chkLstBxPstFilesToSave_Leave(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        private void txtBxAdditionalSubnets_TextChanged(object sender, EventArgs e)
        {
            this.ValidateData();
        }

        #endregion (UI managment)
    }
}
